{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "!pip install -qU langchain-nomic langchain-core langchain-community langchain-google-genai faiss-cpu numpy matplotlib\n",
        "\n",
        "import os\n",
        "import getpass\n",
        "import numpy as np\n",
        "from typing import List, Dict, Any, Optional\n",
        "from dataclasses import dataclass\n",
        "from langchain_nomic import NomicEmbeddings\n",
        "from langchain_core.vectorstores import InMemoryVectorStore\n",
        "from langchain_core.documents import Document\n",
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "import json\n",
        "\n",
        "if not os.getenv(\"NOMIC_API_KEY\"):\n",
        "    os.environ[\"NOMIC_API_KEY\"] = getpass.getpass(\"Enter your Nomic API key: \")\n",
        "\n",
        "if not os.getenv(\"GOOGLE_API_KEY\"):\n",
        "    os.environ[\"GOOGLE_API_KEY\"] = getpass.getpass(\"Enter your Google API key (for Gemini): \")"
      ],
      "metadata": {
        "id": "YcpcDJyKdBDn"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "@dataclass\n",
        "class AgentMemory:\n",
        "    \"\"\"Agent's episodic and semantic memory\"\"\"\n",
        "    episodic: List[Dict[str, Any]]\n",
        "    semantic: Dict[str, Any]\n",
        "    working: Dict[str, Any]\n",
        "\n",
        "class IntelligentAgent:\n",
        "    \"\"\"Advanced AI Agent with Nomic Embeddings for semantic reasoning\"\"\"\n",
        "\n",
        "    def __init__(self, agent_name: str = \"AIAgent\", personality: str = \"helpful\"):\n",
        "        self.name = agent_name\n",
        "        self.personality = personality\n",
        "\n",
        "        self.embeddings = NomicEmbeddings(\n",
        "            model=\"nomic-embed-text-v1.5\",\n",
        "            dimensionality=384,\n",
        "            inference_mode=\"remote\"\n",
        "        )\n",
        "\n",
        "        self.llm = ChatGoogleGenerativeAI(\n",
        "            model=\"gemini-1.5-flash\",\n",
        "            temperature=0.7,\n",
        "            max_tokens=512\n",
        "        )\n",
        "\n",
        "        self.memory = AgentMemory(\n",
        "            episodic=[],\n",
        "            semantic={},\n",
        "            working={}\n",
        "        )\n",
        "\n",
        "        self.knowledge_base = None\n",
        "        self.vector_store = None\n",
        "\n",
        "        self.capabilities = {\n",
        "            \"reasoning\": True,\n",
        "            \"memory_retrieval\": True,\n",
        "            \"knowledge_search\": True,\n",
        "            \"context_awareness\": True,\n",
        "            \"learning\": True\n",
        "        }\n",
        "\n",
        "        print(f\"🤖 {self.name} initialized with Nomic embeddings + Gemini LLM\")\n",
        "\n",
        "    def add_knowledge(self, documents: List[str], metadata: List[Dict] = None):\n",
        "        \"\"\"Add knowledge to agent's semantic memory\"\"\"\n",
        "        if metadata is None:\n",
        "            metadata = [{\"source\": f\"doc_{i}\"} for i in range(len(documents))]\n",
        "\n",
        "        docs = [Document(page_content=doc, metadata=meta)\n",
        "                for doc, meta in zip(documents, metadata)]\n",
        "\n",
        "        if self.vector_store is None:\n",
        "            self.vector_store = InMemoryVectorStore.from_documents(docs, self.embeddings)\n",
        "        else:\n",
        "            self.vector_store.add_documents(docs)\n",
        "\n",
        "        print(f\"📚 Added {len(documents)} documents to knowledge base\")\n",
        "\n",
        "    def remember_interaction(self, user_input: str, agent_response: str, context: Dict = None):\n",
        "        \"\"\"Store interaction in episodic memory\"\"\"\n",
        "        memory_entry = {\n",
        "            \"timestamp\": len(self.memory.episodic),\n",
        "            \"user_input\": user_input,\n",
        "            \"agent_response\": agent_response,\n",
        "            \"context\": context or {},\n",
        "            \"embedding\": self.embeddings.embed_query(f\"{user_input} {agent_response}\")\n",
        "        }\n",
        "        self.memory.episodic.append(memory_entry)\n",
        "\n",
        "    def retrieve_similar_memories(self, query: str, k: int = 3) -> List[Dict]:\n",
        "        \"\"\"Retrieve similar past interactions\"\"\"\n",
        "        if not self.memory.episodic:\n",
        "            return []\n",
        "\n",
        "        query_embedding = self.embeddings.embed_query(query)\n",
        "        similarities = []\n",
        "\n",
        "        for memory in self.memory.episodic:\n",
        "            similarity = np.dot(query_embedding, memory[\"embedding\"])\n",
        "            similarities.append((similarity, memory))\n",
        "\n",
        "        similarities.sort(reverse=True, key=lambda x: x[0])\n",
        "        return [mem for _, mem in similarities[:k]]\n",
        "\n",
        "    def search_knowledge(self, query: str, k: int = 3) -> List[Document]:\n",
        "        \"\"\"Search knowledge base for relevant information\"\"\"\n",
        "        if self.vector_store is None:\n",
        "            return []\n",
        "        return self.vector_store.similarity_search(query, k=k)\n",
        "\n",
        "    def reason_and_respond(self, user_input: str) -> str:\n",
        "        \"\"\"Main reasoning pipeline with context integration\"\"\"\n",
        "\n",
        "        similar_memories = self.retrieve_similar_memories(user_input, k=2)\n",
        "\n",
        "        relevant_docs = self.search_knowledge(user_input, k=3)\n",
        "\n",
        "        context = {\n",
        "            \"similar_memories\": similar_memories,\n",
        "            \"relevant_knowledge\": [doc.page_content for doc in relevant_docs],\n",
        "            \"working_memory\": self.memory.working\n",
        "        }\n",
        "\n",
        "        response = self._generate_contextual_response(user_input, context)\n",
        "\n",
        "        self.remember_interaction(user_input, response, context)\n",
        "\n",
        "        self.memory.working[\"last_query\"] = user_input\n",
        "        self.memory.working[\"last_response\"] = response\n",
        "\n",
        "        return response\n",
        "\n",
        "    def _generate_contextual_response(self, query: str, context: Dict) -> str:\n",
        "        \"\"\"Generate response using Gemini LLM with context\"\"\"\n",
        "\n",
        "        context_info = \"\"\n",
        "\n",
        "        if context[\"relevant_knowledge\"]:\n",
        "            context_info += f\"Relevant Knowledge: {' '.join(context['relevant_knowledge'][:2])}\\n\"\n",
        "\n",
        "        if context[\"similar_memories\"]:\n",
        "            memory = context[\"similar_memories\"][0]\n",
        "            context_info += f\"Similar Past Interaction: User asked '{memory['user_input']}', I responded '{memory['agent_response'][:100]}...'\\n\"\n",
        "\n",
        "        prompt = f\"\"\"You are {self.name}, an AI agent with personality: {self.personality}.\n",
        "\n",
        "Context Information:\n",
        "{context_info}\n",
        "\n",
        "User Query: {query}\n",
        "\n",
        "Please provide a helpful response based on the context. Keep it concise (under 150 words) and maintain your personality.\"\"\"\n",
        "\n",
        "        try:\n",
        "            response = self.llm.invoke(prompt)\n",
        "            return response.content.strip()\n",
        "        except Exception as e:\n",
        "            if context[\"relevant_knowledge\"]:\n",
        "                knowledge_summary = \" \".join(context[\"relevant_knowledge\"][:2])\n",
        "                return f\"Based on my knowledge: {knowledge_summary[:200]}...\"\n",
        "            elif context[\"similar_memories\"]:\n",
        "                last_memory = context[\"similar_memories\"][0]\n",
        "                return f\"I recall a similar question. Previously: {last_memory['agent_response'][:150]}...\"\n",
        "            else:\n",
        "                return \"I need more information to provide a comprehensive answer.\""
      ],
      "metadata": {
        "id": "RDwil0qDdCvY"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class ResearchAgent(IntelligentAgent):\n",
        "    \"\"\"Specialized agent for research and analysis tasks\"\"\"\n",
        "\n",
        "    def __init__(self):\n",
        "        super().__init__(\"ResearchBot\", \"analytical and thorough\")\n",
        "        self.research_domains = []\n",
        "\n",
        "    def analyze_topic(self, topic: str) -> Dict[str, Any]:\n",
        "        \"\"\"Analyze a topic using semantic similarity and Gemini reasoning\"\"\"\n",
        "\n",
        "        related_docs = self.search_knowledge(topic, k=5)\n",
        "\n",
        "        if not related_docs:\n",
        "            return {\"analysis\": \"No relevant information found\", \"confidence\": 0.0}\n",
        "\n",
        "        topic_embedding = self.embeddings.embed_query(topic)\n",
        "        doc_embeddings = [self.embeddings.embed_query(doc.page_content)\n",
        "                         for doc in related_docs]\n",
        "\n",
        "        similarities = [np.dot(topic_embedding, doc_emb)\n",
        "                       for doc_emb in doc_embeddings]\n",
        "\n",
        "        context = \" \".join([doc.page_content for doc in related_docs[:3]])\n",
        "        analysis_prompt = f\"\"\"As a research analyst, analyze the topic: {topic}\n",
        "\n",
        "Available information:\n",
        "{context}\n",
        "\n",
        "Provide a structured analysis including:\n",
        "1. Key insights (2-3 points)\n",
        "2. Confidence level assessment\n",
        "3. Research gaps or limitations\n",
        "4. Practical implications\n",
        "\n",
        "Keep response under 200 words.\"\"\"\n",
        "\n",
        "        try:\n",
        "            gemini_analysis = self.llm.invoke(analysis_prompt)\n",
        "            detailed_analysis = gemini_analysis.content.strip()\n",
        "        except:\n",
        "            detailed_analysis = f\"Analysis of {topic} based on available documents with {len(related_docs)} relevant sources.\"\n",
        "\n",
        "        analysis = {\n",
        "            \"topic\": topic,\n",
        "            \"related_documents\": len(related_docs),\n",
        "            \"max_similarity\": max(similarities),\n",
        "            \"avg_similarity\": np.mean(similarities),\n",
        "            \"key_insights\": [doc.page_content[:100] + \"...\" for doc in related_docs[:3]],\n",
        "            \"confidence\": max(similarities),\n",
        "            \"detailed_analysis\": detailed_analysis\n",
        "        }\n",
        "\n",
        "        return analysis\n",
        "\n",
        "class ConversationalAgent(IntelligentAgent):\n",
        "    \"\"\"Agent optimized for natural conversations\"\"\"\n",
        "\n",
        "    def __init__(self):\n",
        "        super().__init__(\"ChatBot\", \"friendly and engaging\")\n",
        "        self.conversation_history = []\n",
        "\n",
        "    def maintain_conversation_context(self, user_input: str) -> str:\n",
        "        \"\"\"Maintain conversation flow with context awareness\"\"\"\n",
        "\n",
        "        self.conversation_history.append({\"role\": \"user\", \"content\": user_input})\n",
        "\n",
        "        recent_context = \" \".join([msg[\"content\"] for msg in self.conversation_history[-3:]])\n",
        "\n",
        "        response = self.reason_and_respond(recent_context)\n",
        "\n",
        "        self.conversation_history.append({\"role\": \"assistant\", \"content\": response})\n",
        "\n",
        "        return response"
      ],
      "metadata": {
        "id": "ubqngvD-dQHD"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def demonstrate_agent_capabilities():\n",
        "    \"\"\"Comprehensive demonstration of agent capabilities\"\"\"\n",
        "\n",
        "    print(\"🎯 Creating and testing AI agents...\")\n",
        "\n",
        "    research_agent = ResearchAgent()\n",
        "    chat_agent = ConversationalAgent()\n",
        "\n",
        "    knowledge_documents = [\n",
        "        \"Artificial intelligence is transforming industries through automation and intelligent decision-making systems.\",\n",
        "        \"Machine learning algorithms require large datasets to identify patterns and make predictions.\",\n",
        "        \"Natural language processing enables computers to understand and generate human language.\",\n",
        "        \"Computer vision allows machines to interpret and analyze visual information from images and videos.\",\n",
        "        \"Robotics combines AI with physical systems to create autonomous machines.\",\n",
        "        \"Deep learning uses neural networks with multiple layers to solve complex problems.\",\n",
        "        \"Reinforcement learning teaches agents to make decisions through trial and error.\",\n",
        "        \"Quantum computing promises to solve certain problems exponentially faster than classical computers.\"\n",
        "    ]\n",
        "\n",
        "    research_agent.add_knowledge(knowledge_documents)\n",
        "    chat_agent.add_knowledge(knowledge_documents)\n",
        "\n",
        "    print(\"\\n🔬 Testing Research Agent...\")\n",
        "\n",
        "    topics = [\"machine learning\", \"robotics\", \"quantum computing\"]\n",
        "\n",
        "    for topic in topics:\n",
        "        analysis = research_agent.analyze_topic(topic)\n",
        "        print(f\"\\n📊 Analysis of '{topic}':\")\n",
        "        print(f\"   Confidence: {analysis['confidence']:.3f}\")\n",
        "        print(f\"   Related docs: {analysis['related_documents']}\")\n",
        "        print(f\"   Detailed Analysis: {analysis.get('detailed_analysis', 'N/A')[:200]}...\")\n",
        "        print(f\"   Key insight: {analysis['key_insights'][0] if analysis['key_insights'] else 'None'}\")\n",
        "\n",
        "    print(\"\\n💬 Testing Conversational Agent...\")\n",
        "\n",
        "    conversation_inputs = [\n",
        "        \"Tell me about artificial intelligence\",\n",
        "        \"How does machine learning work?\",\n",
        "        \"What's the difference between AI and machine learning?\",\n",
        "        \"Can you explain neural networks?\"\n",
        "    ]\n",
        "\n",
        "    for user_input in conversation_inputs:\n",
        "        response = chat_agent.maintain_conversation_context(user_input)\n",
        "        print(f\"\\n👤 User: {user_input}\")\n",
        "        print(f\"🤖 Agent: {response}\")\n",
        "\n",
        "    print(\"\\n🧠 Memory Analysis...\")\n",
        "    print(f\"Research Agent memories: {len(research_agent.memory.episodic)}\")\n",
        "    print(f\"Chat Agent memories: {len(chat_agent.memory.episodic)}\")\n",
        "\n",
        "    similar_memories = chat_agent.retrieve_similar_memories(\"artificial intelligence\", k=2)\n",
        "    if similar_memories:\n",
        "        print(f\"\\n🔍 Similar memory found:\")\n",
        "        print(f\"   Query: {similar_memories[0]['user_input']}\")\n",
        "        print(f\"   Response: {similar_memories[0]['agent_response'][:100]}...\")"
      ],
      "metadata": {
        "id": "k8teiv11dTc4"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class MultiAgentSystem:\n",
        "    \"\"\"Orchestrate multiple specialized agents\"\"\"\n",
        "\n",
        "    def __init__(self):\n",
        "        self.agents = {\n",
        "            \"research\": ResearchAgent(),\n",
        "            \"chat\": ConversationalAgent()\n",
        "        }\n",
        "        self.coordinator_embeddings = NomicEmbeddings(model=\"nomic-embed-text-v1.5\", dimensionality=256)\n",
        "\n",
        "    def route_query(self, query: str) -> str:\n",
        "        \"\"\"Route query to most appropriate agent\"\"\"\n",
        "\n",
        "        agent_descriptions = {\n",
        "            \"research\": \"analysis, research, data, statistics, technical information\",\n",
        "            \"chat\": \"conversation, questions, general discussion, casual talk\"\n",
        "        }\n",
        "\n",
        "        query_embedding = self.coordinator_embeddings.embed_query(query)\n",
        "        best_agent = \"chat\"\n",
        "        best_similarity = 0\n",
        "\n",
        "        for agent_name, description in agent_descriptions.items():\n",
        "            desc_embedding = self.coordinator_embeddings.embed_query(description)\n",
        "            similarity = np.dot(query_embedding, desc_embedding)\n",
        "\n",
        "            if similarity > best_similarity:\n",
        "                best_similarity = similarity\n",
        "                best_agent = agent_name\n",
        "\n",
        "        return best_agent\n",
        "\n",
        "    def process_query(self, query: str) -> Dict[str, Any]:\n",
        "        \"\"\"Process query through appropriate agent\"\"\"\n",
        "\n",
        "        selected_agent, confidence = self.route_query_with_confidence(query)\n",
        "        agent = self.agents[selected_agent]\n",
        "\n",
        "        if selected_agent == \"research\":\n",
        "            if \"analyze\" in query.lower() or \"research\" in query.lower():\n",
        "                topic = query.replace(\"analyze\", \"\").replace(\"research\", \"\").strip()\n",
        "                result = agent.analyze_topic(topic)\n",
        "                response = f\"Research Analysis: {result.get('detailed_analysis', str(result))}\"\n",
        "            else:\n",
        "                response = agent.reason_and_respond(query)\n",
        "        else:\n",
        "            response = agent.maintain_conversation_context(query)\n",
        "\n",
        "        return {\n",
        "            \"query\": query,\n",
        "            \"selected_agent\": selected_agent,\n",
        "            \"response\": response,\n",
        "            \"confidence\": confidence\n",
        "        }\n",
        "\n",
        "    def route_query_with_confidence(self, query: str) -> tuple[str, float]:\n",
        "        \"\"\"Route query to most appropriate agent and return confidence\"\"\"\n",
        "\n",
        "        agent_descriptions = {\n",
        "            \"research\": \"analysis, research, data, statistics, technical information\",\n",
        "            \"chat\": \"conversation, questions, general discussion, casual talk\"\n",
        "        }\n",
        "\n",
        "        query_embedding = self.coordinator_embeddings.embed_query(query)\n",
        "        best_agent = \"chat\"\n",
        "        best_similarity = 0.0\n",
        "\n",
        "        for agent_name, description in agent_descriptions.items():\n",
        "            desc_embedding = self.coordinator_embeddings.embed_query(description)\n",
        "            similarity = np.dot(query_embedding, desc_embedding)\n",
        "\n",
        "            if similarity > best_similarity:\n",
        "                best_similarity = similarity\n",
        "                best_agent = agent_name\n",
        "\n",
        "        return best_agent, best_similarity"
      ],
      "metadata": {
        "id": "_SsshqHedawJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vKfyXaqrbcQQ",
        "outputId": "4f329836-e4e6-4174-b544-244431a9d759"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "🚀 Advanced AI Agent System with Nomic Embeddings + Gemini LLM\n",
            "======================================================================\n",
            "💡 Note: This uses Google's Gemini 1.5 Flash (free tier) for reasoning\n",
            "📚 Get your free Google API key at: https://makersuite.google.com/app/apikey\n",
            "🎯 Get your Nomic API key at: https://atlas.nomic.ai/\n",
            "======================================================================\n",
            "🎯 Creating and testing AI agents...\n",
            "🤖 ResearchBot initialized with Nomic embeddings + Gemini LLM\n",
            "🤖 ChatBot initialized with Nomic embeddings + Gemini LLM\n",
            "📚 Added 8 documents to knowledge base\n",
            "📚 Added 8 documents to knowledge base\n",
            "\n",
            "🔬 Testing Research Agent...\n",
            "\n",
            "📊 Analysis of 'machine learning':\n",
            "   Confidence: 0.842\n",
            "   Related docs: 5\n",
            "   Detailed Analysis: **Key Insights:**\n",
            "\n",
            "1.  Machine learning's effectiveness is heavily reliant on data volume and quality; larger, cleaner datasets lead to better model performance.\n",
            "2.  Deep learning offers solutions for...\n",
            "   Key insight: Machine learning algorithms require large datasets to identify patterns and make predictions....\n",
            "\n",
            "📊 Analysis of 'robotics':\n",
            "   Confidence: 0.871\n",
            "   Related docs: 5\n",
            "   Detailed Analysis: **1. Key Insights:**\n",
            "\n",
            "* Robotics, fueled by AI advancements, is driving automation across diverse sectors, boosting efficiency and productivity.  \n",
            "* Reinforcement learning significantly enhances robot...\n",
            "   Key insight: Robotics combines AI with physical systems to create autonomous machines....\n",
            "\n",
            "📊 Analysis of 'quantum computing':\n",
            "   Confidence: 0.876\n",
            "   Related docs: 5\n",
            "   Detailed Analysis: **1. Key Insights:**\n",
            "\n",
            "* Quantum computing's exponential speedup for specific problems (e.g., factoring large numbers, drug discovery) presents a disruptive potential across numerous fields.  Its syner...\n",
            "   Key insight: Quantum computing promises to solve certain problems exponentially faster than classical computers....\n",
            "\n",
            "💬 Testing Conversational Agent...\n",
            "\n",
            "👤 User: Tell me about artificial intelligence\n",
            "🤖 Agent: Hey there!  Artificial intelligence is super cool!  Basically, it's about making computers think and learn like humans.  We're talking about machines that can analyze information, make decisions, and even solve problems – all without needing constant human instruction!\n",
            "\n",
            "AI is changing everything, from how we shop online (think personalized recommendations!) to how doctors diagnose illnesses.  It's even powering robots that can do amazing things, like exploring dangerous environments or performing complex surgeries.  It's a rapidly evolving field with tons of exciting possibilities!  Want to know more about a specific application of AI?  Just ask!\n",
            "\n",
            "👤 User: How does machine learning work?\n",
            "🤖 Agent: Hey there!  So you want to know about machine learning?  Awesome!  Think of it like teaching a computer to learn from data without explicitly programming it for every single scenario.  We use something called algorithms – these are like sets of instructions – to help the computer identify patterns and make predictions.\n",
            "\n",
            "Machine learning uses tons of data to build models.  The more data, the better the learning!  It's like showing a child lots of pictures of cats – eventually, they'll recognize a cat even if they've never seen that specific cat before.  This is how things like spam filters, recommendation systems, and even self-driving cars work!  Want to dig deeper into a specific type of machine learning?  Just ask!\n",
            "\n",
            "👤 User: What's the difference between AI and machine learning?\n",
            "🤖 Agent: Hey there!  Great question!  Artificial intelligence (AI) is the broad concept of machines mimicking human intelligence.  Machine learning (ML) is a *subset* of AI.  Think of it this way: AI is the big idea, and ML is one of the tools we use to achieve it.\n",
            "\n",
            "ML specifically focuses on getting computers to learn from data without explicit programming.  AI encompasses many other techniques, including things that don't involve learning from data. So, all machine learning is AI, but not all AI is machine learning!  Want to explore another AI concept? Just ask!\n",
            "\n",
            "👤 User: Can you explain neural networks?\n",
            "🤖 Agent: Hey there!  Neural networks are super cool!  Imagine a web of interconnected nodes, kind of like a brain!  They're the building blocks of deep learning, a powerful type of machine learning.  These nodes process information, passing it along to other nodes in layers.  The more layers, the \"deeper\" the network, and the more complex the problems it can solve.  Think of it like a really sophisticated pattern recognition system.  They're used everywhere from image recognition to language translation – pretty amazing, right? Want to know more about a specific application of neural networks? Just ask!\n",
            "\n",
            "🧠 Memory Analysis...\n",
            "Research Agent memories: 0\n",
            "Chat Agent memories: 4\n",
            "\n",
            "🔍 Similar memory found:\n",
            "   Query: Tell me about artificial intelligence\n",
            "   Response: Hey there!  Artificial intelligence is super cool!  Basically, it's about making computers think and...\n",
            "\n",
            "🎛️ Testing Multi-Agent System...\n",
            "🤖 ResearchBot initialized with Nomic embeddings + Gemini LLM\n",
            "🤖 ChatBot initialized with Nomic embeddings + Gemini LLM\n",
            "📚 Added 3 documents to knowledge base\n",
            "📚 Added 3 documents to knowledge base\n",
            "\n",
            "📝 Query: Analyze the impact of AI on society\n",
            "🎯 Routed to: research agent\n",
            "💬 Response: Research Analysis: 1. **Key Insights:** AI's societal impact is multifaceted.  It boosts productivity through automation (e.g., in manufacturing and c...\n",
            "\n",
            "📝 Query: How are you doing today?\n",
            "🎯 Routed to: chat agent\n",
            "💬 Response: I'm doing great, thanks for asking!  Feeling energized and ready to tackle some exciting data preprocessing challenges.  Have you got any interesting ...\n",
            "\n",
            "📝 Query: Research machine learning trends\n",
            "🎯 Routed to: research agent\n",
            "💬 Response: Research Analysis: **1. Key Insights:**\n",
            "\n",
            "* **Framework Dominance:** TensorFlow and PyTorch's popularity indicates a trend towards robust, community-su...\n",
            "\n",
            "📝 Query: What's your favorite color?\n",
            "🎯 Routed to: chat agent\n",
            "💬 Response: I'm fantastic, thanks!  Ready to dive into some data wrangling too!  Right now I'm playing with a dataset on global temperature anomalies – trying to ...\n",
            "\n",
            "✅ Advanced AI Agent demonstration complete!\n"
          ]
        }
      ],
      "source": [
        "if __name__ == \"__main__\":\n",
        "    print(\"\\n🚀 Advanced AI Agent System with Nomic Embeddings + Gemini LLM\")\n",
        "    print(\"=\" * 70)\n",
        "    print(\"💡 Note: This uses Google's Gemini 1.5 Flash (free tier) for reasoning\")\n",
        "    print(\"📚 Get your free Google API key at: https://makersuite.google.com/app/apikey\")\n",
        "    print(\"🎯 Get your Nomic API key at: https://atlas.nomic.ai/\")\n",
        "    print(\"=\" * 70)\n",
        "\n",
        "    demonstrate_agent_capabilities()\n",
        "\n",
        "    print(\"\\n🎛️ Testing Multi-Agent System...\")\n",
        "    multi_system = MultiAgentSystem()\n",
        "\n",
        "    knowledge_docs = [\n",
        "        \"Python is a versatile programming language used in AI development.\",\n",
        "        \"TensorFlow and PyTorch are popular machine learning frameworks.\",\n",
        "        \"Data preprocessing is crucial for successful machine learning projects.\"\n",
        "    ]\n",
        "\n",
        "    for agent in multi_system.agents.values():\n",
        "        agent.add_knowledge(knowledge_docs)\n",
        "\n",
        "    test_queries = [\n",
        "        \"Analyze the impact of AI on society\",\n",
        "        \"How are you doing today?\",\n",
        "        \"Research machine learning trends\",\n",
        "        \"What's your favorite color?\"\n",
        "    ]\n",
        "\n",
        "    for query in test_queries:\n",
        "        result = multi_system.process_query(query)\n",
        "        print(f\"\\n📝 Query: {query}\")\n",
        "        print(f\"🎯 Routed to: {result['selected_agent']} agent\")\n",
        "        print(f\"💬 Response: {result['response'][:150]}...\")\n",
        "\n",
        "    print(\"\\n✅ Advanced AI Agent demonstration complete!\")"
      ]
    }
  ]
}